package ren.kane.phoenix.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author renrk(1275) on 2018-10-25 4:59 PM
 **/
@Component
@ServerEndpoint("/im/{userId}")
public class ImController {

    private static int onlineCount = 0;

    private static ConcurrentHashMap<String, ImController> webSocketList = new ConcurrentHashMap<>();

    private Session session;

    private String userId = "";

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        webSocketList.put(userId, this);
        addOnlineCount();
        System.out.println("有新连接加入：" + userId + "！当前在线人数为" + getOnlineCount());
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("来自客户端" + userId + "的消息:" + message);

    }

    private void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    private static synchronized int getOnlineCount() {
        return onlineCount;
    }

    private static synchronized void addOnlineCount() {
        ImController.onlineCount++;
    }

    private static synchronized void subOnlineCount() {
        ImController.onlineCount--;
    }
}
